package com.curvebreakers.wheresmystuff.activities;

import com.curvebreakers.wheresmystuff.R;
import com.curvebreakers.wheresmystuff.model.Session;

import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.os.Bundle;

public class HomeActivity extends AuthorizedActivity {
	
	private Fragment tab;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
	
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		ActionBar.Tab dashboardTab = actionBar.newTab().setText("Dashboard");
		ActionBar.Tab searchTab = actionBar.newTab().setText("Search");
		ActionBar.Tab postTab = actionBar.newTab().setText("Post");
		
		dashboardTab.setTabListener(new TabsListener(new DashboardFragment()));
		searchTab.setTabListener(new TabsListener(new EntrySortFragment()));
		postTab.setTabListener(new TabsListener(new CreateEntryFragment()));
		
		actionBar.addTab(dashboardTab);
		actionBar.addTab(searchTab);
		actionBar.addTab(postTab);
		
		if(Session.getSession().isAdmin()){
			ActionBar.Tab adminTab = actionBar.newTab().setText("Admin");
			adminTab.setTabListener(new TabsListener(new AdminFragment()));
			actionBar.addTab(adminTab);
		}
	}
	
	public Fragment getActiveFragment() {
		return tab;
	}
	
	/**
	 * Sets the current tab to be the one at the specified index.
	 * 
	 * @param index
	 */
	public void switchToTab(int index) {
		if (index < getActionBar().getTabCount()) 
			getActionBar().getTabAt(index).select();
	}
	
	/**
	 * ActionBar.TabListener implementation to switch all the tabs in the HomeActivity.
	 */
	private class TabsListener implements ActionBar.TabListener {
		public Fragment fragment;
		 
		public TabsListener(Fragment fragment) {
			this.fragment = fragment;
		}
		 
		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			//DO NOTHING
		}
		 
		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			ft.replace(R.id.fragment_container, fragment);
			HomeActivity.this.tab = fragment;
		}
		 
		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			ft.remove(fragment);
		}
		 
	}
}
